﻿namespace Atomic.Mvc
{
    using System;
    using System.Web;

    /// <summary>
    /// HttpContext 访问器。
    /// </summary>
    public class HttpContextAccessor : IHttpContextAccessor
    {
        /// <summary>
        /// 当前 HttpContext 上下文。
        /// </summary>
        /// <returns>HttpContext 访问器。</returns>
        public HttpContextBase Current()
        {
            var httpContext = this.GetStaticProperty();

            if (httpContext == null)
            {
                return null;
            }

            return new HttpContextWrapper(httpContext);
        }

        /// <summary>
        /// 获得 HttpContext 访问器。
        /// </summary>
        /// <returns>HttpContext 访问器。</returns>
        private HttpContext GetStaticProperty()
        {
            var httpContext = HttpContext.Current;

            if (httpContext == null)
            {
                return null;
            }

            try
            {
                if (httpContext.Request == null)
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }

            return httpContext;
        }
    }
}
